package com.greenant.store.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.bean.AntGoodsBase;
import com.greenant.store.bean.AntGoodsStyles;
import com.greenant.store.bean.AntGoodsStylesBase;
import com.greenant.store.bean.GoodsKind;
import com.greenant.store.bean.GoodsKindBase;
import com.greenant.store.bean.GoodsList;
import com.greenant.store.bean.StoreInfo;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.UtilTools;
import com.greenant.store.view.GetPicMethodDialog;
import com.greenant.store.view.MSpinner;
import com.greenant.store.view.MSpinner.MSpinnerBean;
import com.greenant.store.view.MSpinner.OnMSpinnerItemClickListener;
import com.lsarah.utils.SystemBarTintManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.soundcloud.android.crop.Crop;

public class AddGoodsByhandActivity extends Activity implements OnClickListener, OnMSpinnerItemClickListener {
	private View mViewBack;
	private TextView mTvFinish;
	private ImageView mIvGoodsPic;
	private EditText mEtDescription;
	private EditText mEtPricePurchase;
	private EditText mEtPriceSell;
	private EditText mEtDiscount;
	private EditText mEtPriceByDiscount;
	private EditText mEtStore;
	private EditText mEtSpecs;
	private EditText mEtUnit;
	private EditText mEtWeightUnit;
	private EditText mEtWeightStep;
	private View mViewWeightUnit;
	private View mViewWeightStep;
	private CheckBox mCbWeightableYes;
	private CheckBox mCbWeightableNo;
	private MSpinner mMSpinnerKind;
	private MSpinner mMSpinnerStyle;
	
	public static String KeyScanGoodsBase = "key_scan_goods_base";
	public static String KeyScanCaptureCode = "key_scan_capture_code";
	
	private DecimalFormat mDecimalFormat;
	private StoreInfo mStoreInfo;
	private AntGoodsBase mAntGoods = null;
	private String mCaptureCode = "";
	private Uri mCustomImageUri = null;
	private List<MSpinnerBean> mMSpinnerBeanListKind = new ArrayList<MSpinnerBean>();
	private List<MSpinnerBean> mMSpinnerBeanListStyle = new ArrayList<MSpinnerBean>();
	private List<GoodsKindBase> mGoodsKindBaseList = new ArrayList<GoodsKindBase>();
	private boolean isCommiting = false;
	
	private double mTempPricePurchase = 0;
	private double mTempPriceSell = 0;
	private double mTempDiscount = 0;
	private double mTempStore = 0;
	private double mTempWeightStep = 0;
	private boolean mTempWeightable = false;
//	private String mTempSpecs = "";
//	private String mTempUnit = "";
//	private String mTempWeightUnit = "";
	
	private TextWatcher mTextWatcherForPricePurchase = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double pricePurchase = Double.valueOf(s.toString());
				if(pricePurchase < 0) {
					mEtPricePurchase.setText(String.valueOf(Math.abs(pricePurchase)));
				}
				else {
					mTempPricePurchase = pricePurchase;
				}
			}
			catch(Exception e) {
				mTempPricePurchase = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForPriceSell = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double priceSell = Double.valueOf(s.toString());
				if(priceSell < 0) {
					mEtPriceSell.setText(String.valueOf(Math.abs(priceSell)));
				}
				else {
					mTempPriceSell = priceSell;
					
					if(mTempDiscount > 0) {
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell * mTempDiscount / 10));
					}
					else if(mTempDiscount == 0){
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell));
					}
				}
			}
			catch(Exception e) {
				mTempPriceSell = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForDiscount = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double discount = Double.valueOf(s.toString());
				if(discount < 0) {
					mEtDiscount.setText(String.valueOf(Math.abs(discount)));
				}
				else if(discount > 10) {
					mEtDiscount.setText(String.valueOf(10));
				}
				else {
					mTempDiscount = discount;
					
					if(mTempDiscount > 0) {
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell * mTempDiscount / 10));
					}
					else if(mTempDiscount == 0){
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell));
					}
				}
			}
			catch(Exception e) {
				mTempDiscount = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForStore = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double store = Double.valueOf(s.toString());
				if(store < 0) {
					mEtStore.setText(String.valueOf(Math.abs(store)));
				}
				else {
					mTempStore = store;
				}
			}
			catch(Exception e) {
				mTempStore = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForWeightableStep = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double weightStep = Double.valueOf(s.toString());
				if(weightStep < 0) {
					mEtWeightStep.setText(String.valueOf(Math.abs(weightStep)));
				}
				else {
					mTempWeightStep = weightStep;
				}
			}
			catch(Exception e) {
				mTempWeightStep = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(buttonView.equals(mCbWeightableYes)) {
				if(isChecked) {
					mCbWeightableYes.setEnabled(false);
					mCbWeightableNo.setEnabled(true);
					mCbWeightableNo.setChecked(false);
					mViewWeightStep.setVisibility(View.VISIBLE);
					mViewWeightUnit.setVisibility(View.VISIBLE);
					mTempWeightable = true;
					Log.d("CEXX", "CEXX => onCheckedChanged => mTempWeightable : " + mTempWeightable);
				}
			}
			else if(buttonView.equals(mCbWeightableNo)) {
				if(isChecked) {
					mCbWeightableNo.setEnabled(false);
					mCbWeightableYes.setEnabled(true);
					mCbWeightableYes.setChecked(false);
					mViewWeightStep.setVisibility(View.GONE);
					mViewWeightUnit.setVisibility(View.GONE);
					mTempWeightable = false;
					Log.d("CEXX", "CEXX => onCheckedChanged => mTempWeightable : " + mTempWeightable);
				}
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SystemBarTintManager.setContentView(this, R.layout.add_goods_by_hand, getResources().getColor(R.color.green));
		
		mDecimalFormat = new DecimalFormat("#########.##");
		
		mViewBack = findViewById(R.id.add_goods_by_hand_top_arrow_left);
		mTvFinish = (TextView)findViewById(R.id.add_goods_by_hand_finish);
		mIvGoodsPic = (ImageView)findViewById(R.id.add_goods_byhand_pic);
		mEtDescription = (EditText)findViewById(R.id.add_goods_byhand_description);
		mEtPricePurchase = (EditText)findViewById(R.id.add_goods_byhand_price_purchase_et);
		mEtPriceSell = (EditText)findViewById(R.id.add_goods_byhand_price_sell_et);
		mEtDiscount = (EditText)findViewById(R.id.add_goods_byhand_discount_et);
		mEtPriceByDiscount = (EditText)findViewById(R.id.add_goods_byhand_price_by_discount_et);
		mEtStore = (EditText)findViewById(R.id.add_goods_byhand_store_et);
		mEtSpecs = (EditText)findViewById(R.id.add_goods_byhand_specs_et);
		mEtUnit = (EditText)findViewById(R.id.add_goods_byhand_unit_et);
		mEtWeightUnit = (EditText)findViewById(R.id.add_goods_byhand_weight_unit_et);
		mEtWeightStep = (EditText)findViewById(R.id.add_goods_byhand_weight_step_et);
		mViewWeightUnit = findViewById(R.id.add_goods_byhand_weight_unit_rl);
		mViewWeightStep = findViewById(R.id.add_goods_byhand_weight_step_rl);
		mCbWeightableYes = (CheckBox)findViewById(R.id.add_goods_byhand_weightable_cb_yes);
		mCbWeightableNo = (CheckBox)findViewById(R.id.add_goods_byhand_weightable_cb_no);
		mMSpinnerKind = (MSpinner)findViewById(R.id.add_goods_byhand_mspinner_kind);
		mMSpinnerStyle = (MSpinner)findViewById(R.id.add_goods_byhand_mspinner_style);
		
		mMSpinnerKind.setTitleTextColor(getResources().getColor(android.R.color.black));
		mMSpinnerKind.setTitleGravity(Gravity.CENTER);
		mMSpinnerKind.setHint(getResources().getString(R.string.add_goods_byhand_choose_kind));
		mMSpinnerKind.setOnMSpinnerItemClickListener(this);
		mMSpinnerKind.setDisplayItemInTitle(true);
		mMSpinnerKind.setArrowIcon(R.drawable.icon_dropdown_list);
		
		mMSpinnerStyle.setTitleTextColor(getResources().getColor(android.R.color.black));
		mMSpinnerStyle.setTitleGravity(Gravity.CENTER);
		mMSpinnerStyle.setHint(getResources().getString(R.string.add_goods_byhand_choose_style));
		mMSpinnerStyle.setOnMSpinnerItemClickListener(this);
		mMSpinnerStyle.setDisplayItemInTitle(true);
		mMSpinnerStyle.setArrowIcon(R.drawable.icon_dropdown_list);
		
		mViewBack.setOnClickListener(this);
		mTvFinish.setOnClickListener(this);
		mIvGoodsPic.setOnClickListener(this);
		mEtPricePurchase.addTextChangedListener(mTextWatcherForPricePurchase);
		mEtPriceSell.addTextChangedListener(mTextWatcherForPriceSell);
		mEtDiscount.addTextChangedListener(mTextWatcherForDiscount);
		mEtStore.addTextChangedListener(mTextWatcherForStore);
		mEtWeightStep.addTextChangedListener(mTextWatcherForWeightableStep);
		mCbWeightableYes.setOnCheckedChangeListener(mOnCheckedChangeListener);
		mCbWeightableNo.setOnCheckedChangeListener(mOnCheckedChangeListener);
		
		Intent intent = getIntent();
		mAntGoods = (AntGoodsBase) intent.getSerializableExtra(KeyScanGoodsBase);
		mCaptureCode = intent.getStringExtra(KeyScanCaptureCode);
		Log.d("CEXX", "CEXX => AddGoodsByhandActivity => mAntGoods : " + mAntGoods);
		Log.d("CEXX", "CEXX => AddGoodsByhandActivity => mCaptureCode : " + mCaptureCode);
		if(mAntGoods != null) {
			this.reset(mAntGoods);
		}
		else if(TextUtils.isEmpty(mCaptureCode)) {
			this.reset(null);
		}
		else {
			this.reset(null);
		}
		
		this.retrieveStoreInfo();
		this.retrieveGoodsKindBaseList();
	}

	private void retrieveStoreInfo() {
		if (AntHomeApplication.storeInfos == null || AntHomeApplication.storeInfos.size() == 0) {
			RetrieveDataAsyn.getInstance().getStoreInfoByUserId(-1,
					new RetrieveDataListener() {
						@Override
						public void dataRetrieved(int requestId, Object data) {
							if (AntHomeApplication.storeInfos == null || AntHomeApplication.storeInfos.size() == 0) {
								// 没有获取到StoreInfo数据
							} else {
								// 获取到StoreInfo数据
								List<StoreInfo> storeInfoList = (List<StoreInfo>)data;
								if(storeInfoList.size() > 0) {
									mStoreInfo = storeInfoList.get(0);
								}
							}
						}
					});
		} else {
			// 获取到StoreInfo数据
			Collection<StoreInfo> storeInfos = AntHomeApplication.storeInfos.values();
			for (StoreInfo storeInfo : storeInfos) {
				mStoreInfo = storeInfo;
				break;
			}
		}
		Log.d("CEXX", "CEXX-retrieveStoreInfo-mStoreInfo:" + mStoreInfo);
	}
	
	private void retrieveGoodsKindBaseList() {
		Log.d("CEXX", "CEXX => retrieveGoodsKindList");
		// 请求GoodsKindBase list
		RetrieveDataAsyn.getInstance().getGoodsKindBase(-1, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				List<GoodsKindBase> goodsKindList = (List<GoodsKindBase>)data;
				Log.d("CEXX", "CEXX => retrieveGoodsKindList => goodsKindList : " + goodsKindList);
				if(goodsKindList != null) {
					for(GoodsKindBase gkb : goodsKindList) {
						if(!TextUtils.isEmpty(gkb.getName())) {
							MSpinnerBean bean = new MSpinnerBean();
							bean.contentStr = gkb.getName();
							mMSpinnerBeanListKind.add(bean);
							mGoodsKindBaseList.add(gkb);
						}
					}
					mMSpinnerKind.setDropDownListData(mMSpinnerBeanListKind);
				}
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		if(v.equals(mViewBack)) {
			this.finish();
		}
		else if(v.equals(mIvGoodsPic)) {
			showGetPicMethodDialog();
		}
		else if(v.equals(mTvFinish)) {
			this.checkAndAdd();
		}
	}
	
	private GetPicMethodDialog mGetPicMethodDialog;
	private void showGetPicMethodDialog() {
		mGetPicMethodDialog = new GetPicMethodDialog(this);
		mGetPicMethodDialog.show();
	}
	
	@Override
	public void onMSpinnerItemClick(MSpinner mspinner, int position,
			MSpinnerBean bean) {
		if(mspinner.equals(mMSpinnerKind)) {
			mMSpinnerBeanListStyle.clear();
			
			String kindName = bean.contentStr;
			for(GoodsKindBase gkb : mGoodsKindBaseList) {
				if(kindName.equals(gkb.getName())) {
					List<AntGoodsStylesBase> styleBaseList = gkb.getGoodsStylesList();
					if(styleBaseList != null) {
						for(AntGoodsStylesBase agsb : styleBaseList) {
							if(!TextUtils.isEmpty(agsb.getName())) {
								MSpinnerBean tempBean = new MSpinnerBean();
								tempBean.contentStr = agsb.getName();
								mMSpinnerBeanListStyle.add(tempBean);
							}
						}
					}
					break;
				}
			}
			
			mMSpinnerStyle.setDropDownListData(mMSpinnerBeanListStyle);
		}
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
		if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
            beginCrop(result.getData());
        } else if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, result);
        } else if (resultCode == RESULT_OK
                && requestCode == GetPicMethodDialog.RequestCodeTakePhoto) {
            // 使用相机拍摄的图片
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Log.d("CEXX", "CEXX => AddGoodsByhandActivity => RequestCodeTakePhoto");
                handlePicByTakePhoto();
            }
        }
    }
	
	private void handlePicByTakePhoto() {
		if (mGetPicMethodDialog == null || mGetPicMethodDialog.mExtraOutputUri == null) {
        	return;
        }
		
		Uri picUri = mGetPicMethodDialog.mExtraOutputUri;
		String picPath = picUri.getPath();
		Log.d("CEXX", "CEXX => handlePicByTakePhoto => picPath : " + picPath);
		
		// 获取图片的旋转角度，有些系统把拍照的图片旋转了，有的没有旋转
		int degree = readPictureDegree(picPath);
		Log.d("CEXX", "CEXX => handlePicByTakePhoto => degree : " + degree);
		
		if(degree == 0) {
			beginCrop(picUri);
		} 
		else {
			Bitmap picBitmap = BitmapFactory.decodeFile(picPath);
			if(picBitmap == null) {
				beginCrop(picUri);
				return;
			}
			
			// 把图片旋转为正的方向
			Bitmap newbitmap = rotaingImageView(degree, picBitmap);
			picBitmap.recycle();
			if(newbitmap == null) {
				beginCrop(picUri);
				return;
			}
			
			saveBitmap(newbitmap, picPath);
			newbitmap.recycle();
			beginCrop(picUri);
		}
	}
	
	public void saveBitmap(Bitmap bitmap, String savePath) {
		try {
			File f = new File(savePath);
			if(f.exists()) {
				f.delete();
			}
			FileOutputStream fos = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 旋转图片
	 * 
	 * @param angle
	 * 
	 * @param bitmap
	 * 
	 * @return Bitmap
	 */
	public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		;
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}
	
	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}
	
	private void reset(AntGoodsBase antGoodsBase) {
		if(antGoodsBase != null) {
			// AntGoodsBase中有的属性
			mEtDescription.setText(antGoodsBase.getDescription()==null ? "" : antGoodsBase.getDescription());
			mEtUnit.setText(antGoodsBase.getWeighUnit()==null ? "" : antGoodsBase.getWeighUnit());
			mEtWeightUnit.setText(antGoodsBase.getUnit()==null ? "" : antGoodsBase.getUnit());
			mEtWeightStep.setText(""+antGoodsBase.getWeighStep());
			mMSpinnerKind.setText(antGoodsBase.getKind());
			mMSpinnerStyle.setText(antGoodsBase.getStyle());
			
			if(antGoodsBase.isWeighAble()) {
				mCbWeightableYes.setChecked(true);
				mCbWeightableNo.setChecked(false);
			}
			else {
				mCbWeightableYes.setChecked(false);
				mCbWeightableNo.setChecked(true);
			}
			
			mIvGoodsPic.setScaleType(ScaleType.FIT_XY);
			mIvGoodsPic.setImageDrawable(null);
			if(!TextUtils.isEmpty(antGoodsBase.getImageUrl())) {
				ImageLoader.getInstance().displayImage(antGoodsBase.getImageUrl(), 
						mIvGoodsPic, AntHomeApplication.imageDisplayOptions);
			}
			
			// AntGoodsBase中没有的属性
			mEtPricePurchase.setText("");
			mEtPriceSell.setText("");
			mEtStore.setText("");
			mEtDiscount.setText("");
			mEtPriceByDiscount.setText("");
			mEtSpecs.setText("");
			
			this.enabledSet(true);
		}
		else {
			mEtDescription.setText("");
			mEtUnit.setText("");
			mEtWeightUnit.setText("");
			mEtWeightStep.setText("");
			mMSpinnerKind.setText("");
			mMSpinnerStyle.setText("");
			mCbWeightableYes.setChecked(false);
			mCbWeightableNo.setChecked(true);
			mIvGoodsPic.setScaleType(ScaleType.CENTER);
			mIvGoodsPic.setImageResource(R.drawable.ic_kdwd_diary_add);
			
			mEtPricePurchase.setText("");
			mEtPriceSell.setText("");
			mEtStore.setText("");
			mEtDiscount.setText("");
			mEtPriceByDiscount.setText("");
			mEtSpecs.setText("");
			
			this.enabledSet(false);
		}
	}
	
	/**
	 *  AntGoodsBase不允许修改的属性(从在线库中添加的商品，编辑商品时，只能编辑进价，售价和库存)
	 */
	private void enabledSet(boolean isFromLib) {
		if(isFromLib) {
			mCbWeightableNo.setEnabled(false);
			mCbWeightableYes.setEnabled(false);
			mEtDiscount.setEnabled(false);
			mEtPriceByDiscount.setEnabled(false);
			mEtSpecs.setEnabled(false);
			mEtUnit.setEnabled(false);
			mEtWeightUnit.setEnabled(false);
			mEtWeightStep.setEnabled(false);
			mMSpinnerKind.setEnabled(false);
			mMSpinnerStyle.setEnabled(false);
		}
		else {
			mCbWeightableYes.setEnabled(true);
			mCbWeightableNo.setEnabled(false);
			mEtDiscount.setEnabled(true);
			mEtPriceByDiscount.setEnabled(true);
			mEtSpecs.setEnabled(true);
			mEtUnit.setEnabled(true);
			mEtWeightUnit.setEnabled(true);
			mEtWeightStep.setEnabled(true);
			mMSpinnerKind.setEnabled(true);
			mMSpinnerStyle.setEnabled(true);
		}
	}

    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().withMaxSize(350, 350).start(this);
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
        	mIvGoodsPic.setScaleType(ScaleType.FIT_XY);
        	mIvGoodsPic.setImageDrawable(null);
        	mCustomImageUri = Crop.getOutput(result);
        	mIvGoodsPic.setImageURI(mCustomImageUri);
        	Log.d("CEXX", "CEXX => handleCrop => mCustomImageUri : " + mCustomImageUri);
        	Log.d("CEXX", "CEXX => handleCrop => mCustomImageUri.getPath : " + mCustomImageUri.getPath());
        	Log.d("CEXX", "CEXX => handleCrop => mCustomImageUri.getLastPathSegment : " + mCustomImageUri.getLastPathSegment());
        } else if (resultCode == Crop.RESULT_ERROR) {
            Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void checkAndAdd() {
    	if(isCommiting) {
    		UtilTools.showMyToast(this, getResources().getString(R.string.prompt_is_commiting));
    		return;
    	}
    	
    	if(mAntGoods == null) {
    		if(mCustomImageUri == null) {
    			// 检查商品图片
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_pic));
    			return;
    		}
    		else if(TextUtils.isEmpty(mEtDescription.getText().toString())) {
    			// 检查商品描述
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_des));
    			return;
    		}
    		else if(TextUtils.isEmpty(mMSpinnerKind.getText())) {
    			// 检查商品大类
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_kind));
    			return;
    		}
    		else if(TextUtils.isEmpty(mMSpinnerStyle.getText())) {
    			// 检查商品小类
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_style));
    			return;
    		}
    		else if(TextUtils.isEmpty(mEtPricePurchase.getText().toString())) {
    			// 检查商品进价
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_purchase));
    			return;
    		}
    		else if(TextUtils.isEmpty(mEtPriceSell.getText().toString())) {
    			// 检查商品售价
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_sell));
    			return;
    		}
    		else if(TextUtils.isEmpty(mEtStore.getText().toString())) {
    			// 检查商品库存
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_store));
    			return;
    		}
//    		else if(TextUtils.isEmpty(mEtSpecs.getText().toString())) {
//    			// 检查商品规格
//    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_specs));
//    			return;
//    		}
    		else if(TextUtils.isEmpty(mEtUnit.getText().toString())) {
    			// 检查商品计价单位
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_unit));
    			return;
    		}
    		else if(mCbWeightableYes.isChecked()) {
    			// 检查称重单位
    			if(TextUtils.isEmpty(mEtWeightUnit.getText().toString())) {
    				UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_weightunit));
    				return;
    			}
    			// 检查最小称重
    			if(TextUtils.isEmpty(mEtWeightStep.getText().toString())) {
    				UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_weightstep));
    				return;
    			}
    		} 
    		
    		isCommiting = true;
    		goodsAdd();
    	}
    	else {
    		if(TextUtils.isEmpty(mEtPriceSell.getText().toString())) {
    			// 检查商品售价
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_sell));
    			return;
    		}
    		else if(TextUtils.isEmpty(mEtStore.getText().toString())) {
    			// 检查商品库存
    			UtilTools.showMyToast(this, getResources().getString(R.string.add_goods_check_prompt_store));
    			return;
    		}
    		
    		List<String> storeIdList = new ArrayList<String>();
    		if(mStoreInfo != null) {
    			storeIdList.add(mStoreInfo.getStoreid());
    		}
    		isCommiting = true;
    		RetrieveDataAsyn.getInstance().getGoodsBySrcId(storeIdList, mAntGoods.getObjectId(), -1, new RetrieveDataListener() {
    			@Override
    			public void dataRetrieved(int requestId, Object data) {
    				GoodsList goodsList = (GoodsList)data;
    				Log.d("CEXX", "CEXX => saveStyle => goodsList.getTotalNum : " + goodsList.getTotalNum());
    				if(goodsList.getGoodList() == null || goodsList.getGoodList().size() == 0) {
    					goodsAdd();
    				}
    				else {
    					isCommiting = false;
    					Toast.makeText(
    							AddGoodsByhandActivity.this,
    							R.string.add_goods_dialog_prompt_double,
    							Toast.LENGTH_SHORT).show();
    				}
    			}
    		});
    	}
	}
    
    private void goodsAdd() {
		AlertDialog dialog = new AlertDialog.Builder(this)
				.setTitle(R.string.order_ensure_order_commit_prompt)
				.setMessage(R.string.add_goods_dialog_prompt_add)
				.setNegativeButton(R.string.sure,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								saveStyle();
							}
						})
				.setPositiveButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								isCommiting = false;
							}
						}).create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.show();
	}
	
	private void saveStyle() {
		String styleName = "";
		if(mAntGoods == null) {
			styleName = mMSpinnerStyle.getText();
		}
		else {
			styleName = mAntGoods.getStyle();
		}
		Log.d("CEXX", "CEXX => saveStyle => styleName : " + styleName);
		AntGoodsStyles style = new AntGoodsStyles();
		style.setName(styleName);
		style.setUserId(AVUser.getCurrentUser().getObjectId());
		RetrieveDataAsyn.getInstance().checkAndSaveStyle(style, 0, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				AntGoodsStyles style = (AntGoodsStyles)data;
				Log.d("CEXX", "CEXX => saveStyle => style.getObjectId : " + style.getObjectId());
				saveKind(style);
			}
		});
		
//		style.saveInBackground(new SaveCallback() {
//			@Override
//			public void done(AVException arg0) {
//				if (arg0 == null) {
//					Log.d("CEXX", "CEXX => saveStyle => suc=> style.getObjectId : " + style.getObjectId());
//					saveKind(style);
//				} else {
//					Log.d("CEXX", "CEXX => saveStyle => fai => Exception : " + arg0.toString());
//					Toast.makeText(
//							AddGoodsByhandActivity.this,
//							R.string.goods_handle_attr_modify_prompt_failed,
//							Toast.LENGTH_SHORT).show();
//				}
//			}
//		});
	}
	
	private void saveKind(AntGoodsStyles style) {
		String kindName = "";
		if(mAntGoods == null) {
			kindName = mMSpinnerKind.getText();
		}
		else {
			kindName = mAntGoods.getKind();
		}
		Log.d("CEXX", "CEXX => saveKind => kindName : " + kindName);
		GoodsKind kind = new GoodsKind();
		kind.setName(kindName);
		kind.setUserId(AVUser.getCurrentUser().getObjectId());
		kind.getStyleRelation().add(style);
		RetrieveDataAsyn.getInstance().checkAndSaveKind(kind, style, 0, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				GoodsKind kind = (GoodsKind)data;
				Log.d("CEXX", "CEXX => saveKind => kind.getObjectId : " + kind.getObjectId());
				saveGoods();
			}
		});
		
//		kind.saveInBackground(new SaveCallback() {
//			@Override
//			public void done(AVException arg0) {
//				if (arg0 == null) {
//					Log.d("CEXX", "CEXX => saveKind => suc");
//					saveGoods();
//				} else {
//					Log.d("CEXX", "CEXX => saveKind => fai => Exception : " + arg0.toString());
//					Toast.makeText(
//							AddGoodsByhandActivity.this,
//							R.string.goods_handle_attr_modify_prompt_failed,
//							Toast.LENGTH_SHORT).show();
//				}
//			}
//		});
	}
	
	private void saveGoods() {
		if(mStoreInfo == null) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(
							AddGoodsByhandActivity.this,
							R.string.goods_handle_attr_modify_prompt_failed_no_store,
							Toast.LENGTH_SHORT).show();
				}
			});
			isCommiting = false;
			return;
		}
		
		AntGoods antGoods = new AntGoods();
		
		if(mAntGoods != null) {
			// AntGoodsBase中有的属性
			antGoods.setDescription(mAntGoods.getDescription());
			antGoods.setUnit(mAntGoods.getUnit());
			antGoods.setWeighUnit(mAntGoods.getWeighUnit());
			antGoods.setWeighStep(mAntGoods.getWeighStep());
			antGoods.setKind(mAntGoods.getKind());
			antGoods.setStyle(mAntGoods.getStyle());
			antGoods.setWeighAble(mAntGoods.isWeighAble());
			antGoods.setImageFile(mAntGoods.getImageAVFile());
			
			// AntGoodsBase中没有的属性
			antGoods.setInPrice(mTempPricePurchase);
			antGoods.setPrice(mTempPriceSell);
			antGoods.setStock(mTempStore);
			antGoods.setDiscount(mTempDiscount);
			antGoods.setSpecs(mEtSpecs.getText().toString());
			
			antGoods.setUserId(mStoreInfo.getStoreid());
			antGoods.setStoreId(mStoreInfo.getStoreid());
			antGoods.setShowTag(0);
			antGoods.setSrcId(mAntGoods.getObjectId());
			antGoods.setTotalSales(0);
			antGoods.setIsFromLib(true);
		}
		else {
			antGoods.setDescription(mEtDescription.getText().toString());
			antGoods.setUnit(mEtUnit.getText().toString());
			antGoods.setWeighUnit(mEtWeightUnit.getText().toString());
			antGoods.setWeighStep(mTempWeightStep);
			antGoods.setKind(mMSpinnerKind.getText());
			antGoods.setStyle(mMSpinnerStyle.getText());
			antGoods.setWeighAble(mTempWeightable);
			if(mCustomImageUri != null) {
				try {
					AVFile avFile = AVFile.withAbsoluteLocalPath(
							antGoods.getDescription(), mCustomImageUri.getPath());
					antGoods.setImageFile(avFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			antGoods.setInPrice(mTempPricePurchase);
			antGoods.setPrice(mTempPriceSell);
			antGoods.setStock(mTempStore);
			antGoods.setDiscount(mTempDiscount);
			antGoods.setSpecs(mEtSpecs.getText().toString());
			
			antGoods.setUserId(mStoreInfo.getStoreid());
			antGoods.setStoreId(mStoreInfo.getStoreid());
			antGoods.setShowTag(0);
			antGoods.setSrcId("");
			antGoods.setTotalSales(0);
			antGoods.setIsFromLib(false);
		}
		
		antGoods.saveInBackground(new SaveCallback() {
			@Override
			public void done(AVException arg0) {
				isCommiting = false;
				if (arg0 == null) {
					Log.d("CEXX", "CEXX => saveGoods => suc");
					Toast.makeText(
							AddGoodsByhandActivity.this,
							R.string.goods_handle_attr_modify_prompt_successful,
							Toast.LENGTH_SHORT).show();
					finish();
				} else {
					Log.d("CEXX", "CEXX => saveGoods => fai => Exception : " + arg0.toString());
					Toast.makeText(
							AddGoodsByhandActivity.this,
							R.string.goods_handle_attr_modify_prompt_failed,
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
}






















